<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/11
 * Time: 16:52
 */

namespace Admin\Service;


use Admin\Model\AdminUserModel;

class MenuService
{
    // 获取用户菜单
    public function getUserMenu($user_id)
    {
        $menus = yaml_parse_file(CONF_PATH . 'admin.yaml');

        $userMdl = new AdminUserModel();
        $user = $userMdl->find($user_id);

        $user_rights = json_decode(htmlspecialchars_decode($user['rights']), true);

        if ($user['type'] == 0) {
            return $menus;
        }

        // 第一次遍历筛选菜单
        foreach ($menus['menus'] as $key => &$menu) {
            foreach ($menu['nav_menu'] as $nav_key => &$nav_menu) {
                foreach ($nav_menu['third_menu'] as $third_key => &$third_menu) {
                    foreach ($user_rights as $right) {
                        if ($third_menu['title'] == $right['title'] && $right['level'] == 2) {
                            $third_menu['enable'] = true;
                        }
                    }
                }

                foreach ($user_rights as $right) {
                    if ($nav_menu['title'] == $right['title'] && $right['level'] == 1) {
                        $nav_menu['enable'] = true;
                    }
                }
            }

            foreach ($user_rights as $right) {
                if ($menu['title'] == $right['title'] && $right['level'] == 0) {
                    $menu['enable'] = true;
                }
            }
        }

        // 第二次遍历去除无效菜单
        foreach ($menus['menus'] as $key => &$menu) {
            foreach ($menu['nav_menu'] as $nav_key => &$nav_menu) {
                foreach ($nav_menu['third_menu'] as $third_key => &$third_menu) {
                    if ($third_menu['enable'] != true) {
                        array_splice($nav_menu['third_menu'], $third_key, 1);
                    }
                }

                if ($nav_menu['enable'] != true) {
                    array_splice($menu['nav_menu'], $nav_key, 1);
                }
            }

            if ($menu['enable'] != true) {
                array_splice($menus['menus'], $key, 1);
            }
        }

        return $menus;
    }

}